/**
 * 计算sign值的封装
 * Created by json on 2018/8/24.
 */

import Enc from '../utils/enc.util';
import LocalStorage from './localstorage.service';

/**
 * 保存参数中的数据到数组
 * @param params
 * @returns {Array}
 */
const saveDataToArray = params => {
  let tempArr = [];
  for (let i in params) {
    if (Object.hasOwnProperty.call(params, i) && i !== 'sign') {
      tempArr.push(
        i.toString() + (params[i] === undefined ? '' : params[i]) + ''
      );
    }
  }
  return tempArr;
};

/**
 * 数组排序
 * @param data {Array}
 * @returns {string}
 */
const sortData = data => {
  let tempData = [].concat(data);
  tempData.sort();
  return tempData.join('');
};

/**
 * 计算md5值
 * @param str
 * @returns {[*,*]}
 */
const md5Encode = str => {
  return [Enc.md5(str), str];
};

/**
 * 获取旧版固定des key  主要是用于geetest滑动验证， 获取手机号等代理上的接口
 * @return {string}
 */
const getOldDesKey = function () {
  let result = '';
  let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let keyArr = [
    5, 5, 27, 35, 0, 3, 27, 29, 27, 33, 3, 29, 32, 35, 4, 2, 33, 30, 27, 3, 4,
    32, 32, 33, 35, 5, 5, 3, 2, 34, 33, 2
  ];
  for (let i = 0, l = keyArr.length; i < l; i++) {
    result += str.substr(keyArr[i], 1);
  }
  return result;
};

/**
 * des 加密
 * @param str
 * @param sortedParams
 * @returns {*}
 */
const desEncrypt = (str, sortedParams) => {
  let key = '';
  if (isOldKey) {
    key = getOldDesKey() || '';
  } else {
    key = LocalStorage.getSignKey() || '';
  }
  if (key.length > 0) {
    return [Enc.desEncrypt(key, str), sortedParams];
  } else {
    return ['', sortedParams];
  }
};

/**
 * 得出sign值
 * @param desEncrypted {string}
 * @param sortedParams {string}
 * @returns {string}
 */
const getSign = (desEncrypted, sortedParams) => {
  if (desEncrypted.length > 0) {
    return Enc.md5(sortedParams + desEncrypted);
  } else {
    return '';
  }
};

/**
 * 计算sign值
 * @param data
 * @returns {*}
 */
let isOldKey = false;
const computeSign = datas => {
  let data = null;
  isOldKey = false;
  if (datas.url && datas.url.indexOf('openInter') > -1) {
    isOldKey = true;
    data = datas.data;
  } else if (
    datas.url &&
    datas.url.indexOf('pushUserValidateCodeMyInter') > -1
  ) {
    data = datas.data;
  } else if (datas.url) {
    data = datas.data;
  } else {
    data = datas;
  }

  let result = Object.assign({}, data);

  let computeArr = [saveDataToArray, sortData, md5Encode, desEncrypt, getSign];

  for (let i = 0, l = computeArr.length; i < l; i++) {
    Array.isArray(result) === false ? (result = [result]) : '';
    if (i === 1) {
      result = [result];
    }
    result = computeArr[i].apply({}, result);
  }

  if (result.length > 0) {
    data['sign'] = result;
  }
  return data;
};

export default computeSign;
